package mqttsub

import (
	watchtcp "earth/watch_tcp"
	"log"

	tpprotocolsdkgo "github.com/ThingsPanel/tp-protocol-sdk-go"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var MqttClient *tpprotocolsdkgo.MQTTClient

func InitClient() {
	logrus.Info("创建mqtt订阅客户端")
	// 创建新的MQTT客户端实例
	addr := viper.GetString("mqtt.broker")
	var username, password string
	if viper.GetString("version") == "new" {
		username = viper.GetString("mqtt.username")
		password = viper.GetString("mqtt.password")
	} else {
		username = viper.GetString("mqtt.username_old")
		password = viper.GetString("mqtt.password_old")
	}
	client := tpprotocolsdkgo.NewMQTTClient(addr, username, password)
	// 尝试连接到MQTT代理
	if err := client.Connect(); err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	logrus.Info("连接成功")
	MqttClient = client
	// 订阅平台的命令
	subscribeCommand()
}

// 订阅命令消息
func subscribeCommand() {
	// 订阅消息
	if viper.GetString("version") == "new" {
		if err := MqttClient.Subscribe(viper.GetString("mqtt.topic_to_subscribe_command"), func(client mqtt.Client, msg mqtt.Message) {
			logrus.Debug("接收主题:", msg.Topic())
			logrus.Debug("\ni<==接收消息:", string(msg.Payload()))
			err := watchtcp.DealTpCommand(msg.Topic(), msg.Payload())
			if err != nil {
				logrus.Warn("处理消息失败:", err)
			}
		}, 0); err != nil {
			logrus.Warn("订阅消息失败:", err)
		}
	} else {
		if err := MqttClient.Subscribe(viper.GetString("mqtt.topic_to_subscribe_command_old"), func(client mqtt.Client, msg mqtt.Message) {
			logrus.Debug("接收主题:", msg.Topic())
			logrus.Debug("\ni<==接收消息:", string(msg.Payload()))
			err := watchtcp.DealTpCommand(msg.Topic(), msg.Payload())
			if err != nil {
				logrus.Warn("处理消息失败:", err)
			}
		}, 0); err != nil {
			logrus.Warn("订阅消息失败:", err)
		}
	}
}

// 订阅
func Subscribe() {
	// 主题
	topic := viper.GetString("mqtt.topic_to_subscribe")
	qos := viper.GetUint("mqtt.qos")
	// 订阅主题
	if err := MqttClient.Subscribe(topic, messageHandler, uint8(qos)); err != nil {
		log.Printf("订阅主题失败: %v", err)
	}
	log.Println("订阅主题成功:", topic)

}

// 设备下发消息的回调函数：主题plugin/modbus/# payload：{sub_device_addr:{key:value...},sub_device_addr:{key:value...}}
func messageHandler(client mqtt.Client, msg mqtt.Message) {
	log.Printf("收到消息: %s", msg.Payload())
}
